/**
 * 实体属性
 */
import DomainProperty from './DomainProperty.js';
import EntityPropertyMapping from './EntityPropertyMapping.js';
import EmbeddedPropertyMapping from './EmbeddedPropertyMapping.js';
import TypeKind from '../enums/TypeKind.js';

export default class EntityProperty extends DomainProperty {

    primary = false;
    belongs = false;
    /**
     *
     * @type {EntityPropertyMapping}
     */
    mapping = null;
    /**
     * @type {[EmbeddedPropertyMapping]}
     */
    embedded = [];

    static of(object) {
        if (typeof object !== 'object') {
            return undefined;
        }
        let property = new EntityProperty();
        property.update(object);
        return property;
    }

    update(object) {
        super.update(object);
        if (typeof object === 'object') {
            if (object.mapping) {
                this.mapping = EntityPropertyMapping.of(object.mapping);
            }
            if (object.embedded) {
                this.embedded = object.embedded.map(field => {
                    return EmbeddedPropertyMapping.of(field);
                });
            }
        }
        return this;
    }

    clone() {
        return EntityProperty.of(this);
    }

    getDefaultPhysicalFieldName() {
        if (!this.name) {
            return '';
        }
        let array = this.name.splitByUpperCaseLetter();
        let mappingName = array.join('_').toLowerCase();
        if (this.refKind && TypeKind.UNITY.equals(this.refKind)) {
            mappingName += '_id';
        }
        if (this.arrayed) {
            if (mappingName.endsWith('s')) {
                mappingName = mappingName.substring(0, mappingName.length - 1);
            }
            mappingName += '_string';
        }
        return mappingName;
    }

}
